package com.example.shiwu;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.ViewStub;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.example.shiwu.adapter.GpsAdapter;
import com.example.shiwu.adapter.GpsAdapter;
import com.example.shiwu.adapter.SendReceiveAdapter;
import com.example.shiwu.db.model.BoxOne;
import com.example.shiwu.db.model.Device;
import com.example.shiwu.db.model.Items;
import com.example.shiwu.db.model.Sends;
import com.example.shiwu.db.vo.GpsVo;
import com.example.shiwu.manager.DatabaseHelper;
import com.example.shiwu.service.ItemsService;
import com.example.shiwu.service.SendsService;
import com.example.shiwu.util.BoxUtil;
import com.example.shiwu.util.FileDownUtil;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by Jay on 2015/11/20 0020.
 */
public class GpsListActivity extends AppCompatActivity implements GpsAdapter.MyClickListener{
    private Context myContent;
    public TextView title_text,title_seting,title_add,did;
    public ImageView title_back;
    private Button item_del_btn;
    private String ids = "";
    private List<Integer> idlis = new ArrayList<Integer>();
    private DatabaseHelper dbHelper;
    private Button allCheak;
    private RefreshLayout mRefreshLayout;
    private ListView listView;
    private int currentPage = 1;
    private int pageSize = 2;
    private ArrayList<GpsVo> sendLisAll = null;
    private boolean checkSta = false;
    private ItemsService itemsService;
    private SendsService sendService;
    private GpsAdapter myAdapter;
    private CheckBox checkBox,send_items_checkbox;

    @SuppressLint("MissingPermission")
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gps);
        myContent = this;
        title_back = findViewById(R.id.title_back_add);
        title_text = findViewById(R.id.title_text);
        title_add = findViewById(R.id.title_add);
        item_del_btn = findViewById(R.id.item_del_btn);
        allCheak = findViewById(R.id.allCheak);
        title_text.setText("GPS坐标记录");
        sendLisAll = new ArrayList<GpsVo>();
        dbHelper = new DatabaseHelper(this);
        listView = findViewById(R.id.gps_list_view);
        title_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(myContent, GpsAddActivity.class);
                startActivity(intent);
            }
        });
        title_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                GpsListActivity.this.finish();
            }
        });

        this.getDeviceLisAll();

        item_del_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("——————————————删除——————————————————");
                String ids1 = ids.substring(0,ids.length()-1);
                List<String> idLis = new ArrayList<>();
                if(ids1.length()>1){
                    String[] idLis1 = ids1.split(",");
                    idLis.addAll(Arrays.asList(idLis1));
                }else{
                    idLis.add(ids1);
                }

                if(idLis.size()>0){
                    for (int i = 0; i < idLis.size(); i++) {
                        BoxUtil.updateBox(idLis.get(i));
                    }
                    updataData();
                }
            }
        });

        mRefreshLayout = findViewById(R.id.refreshLayout);
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() { //下拉刷新
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getItemsDataHeaderPull();
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
            }
        });

        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() { //上拉加载更多
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                getItemsDataFooterPull();
                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            }
        });



        Items items = null;
        try {
            items = findSelectItem();
            if(null != items){
                Device dev = new Device();
                dev.setItemId(String.valueOf(items.getId()));
                //int count = getDeviceLisAllCount();
                int count =sendLisAll.size();
                if(count>0){
                    allCheak.setOnClickListener(new  View.OnClickListener(){
                        @Override
                        public void onClick(View view) {
                            if(checkSta){
                                btnNoList();
                                allCheak.setText("全选");
                            }else{
                                btnSelectAllList();
                                allCheak.setText("全不选");
                            }

                        }
                    });
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        updataData();
    }
    private Items findSelectItem(){
        itemsService = new ItemsService();
        Items items = new Items();
        Items items1 = new Items();
        items.setStatus(1);
        List<Items> lis = null;

        try {
            lis = itemsService.getItems(items);
            items1 = lis.get(0);
        }catch (Exception e){
            e.printStackTrace();
        }
        return items1;
    }

    private List<GpsVo> performJoinQuery(String itemId) {
        int limit = (currentPage-1)*pageSize;
        String type = "0";
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        // SQL语句：查询用户表和订单表，根据用户ID关联
        Cursor cursor = db.query("tb_boxOne box left join  tb_items ite on ite.id = box.item_id left join tb_device dev on dev.item_id = ite.id ",
                new String[]{"box.id, ite.name, box.item_id, ite.operator, dev.sn as deviceId, box.create_time "},
                "ite.id = ?",
                new String[]{itemId},"box.id","","box.item_id DESC", String.valueOf(limit)+","+String.valueOf(pageSize));
        System.out.println(cursor.getCount());
        List<GpsVo> lis = new ArrayList<>();
        // 遍历结果集
        while (cursor.moveToNext()) {
            GpsVo GpsVo = new GpsVo();
            String id = cursor.getString(0);
            GpsVo.setId(id);
            String name = cursor.getString(1);
            GpsVo.setName(name);
            int itemId1 = cursor.getInt(2);
            GpsVo.setItemId(itemId1);
            String operator = cursor.getString(3);
            GpsVo.setOperator(operator);
            String deviceId = cursor.getString(4);
            GpsVo.setDeviceId(deviceId);
            String create_time = cursor.getString(5);
            GpsVo.setCreateTime(create_time);
            lis.add(GpsVo);
            // 处理查询结果
            // ...
        }

        cursor.close();
        db.close();
        return lis;
    }
    public void updataData(){
        sendLisAll = new ArrayList<GpsVo>();
        currentPage = 1;
        getDeviceLisAll();
        myAdapter.cleckAll();
    }
    public void getDeviceLisAll() {
        Resources res =getResources();
        String[] modeData=res.getStringArray(R.array.modeData);

        Items item = findSelectItem();
        //List<GpsVo> send = sendService.getAll((currentPage * pageSize), pageSize,item.getId(),0);
        List<GpsVo> send = performJoinQuery(String.valueOf(item.getId()));
        currentPage+=1;
        sendLisAll.addAll(send);
        //创建一个simpleAdapter
        myAdapter = new GpsAdapter(GpsListActivity.this, sendLisAll, R.layout.gps_list_item,modeData,this);
        //listView = findViewById(R.id.gps_list_view);
        listView.setAdapter(myAdapter);
    }
    private void getItemsDataHeaderPull() {
        Resources res =getResources();
        String[] modeData=res.getStringArray(R.array.modeData);
        Items item = findSelectItem();
        currentPage =1;
        sendLisAll= null;
        sendLisAll = new ArrayList<GpsVo>();
        //List<GpsVo> send = sendService.getAll((currentPage * pageSize), pageSize,item.getId(),0);
        List<GpsVo> send = performJoinQuery(String.valueOf(item.getId()));
        currentPage+=1;
        sendLisAll.addAll(send);
        //创建一个simpleAdapter
        myAdapter = new GpsAdapter(GpsListActivity.this, sendLisAll, R.layout.gps_list_item,modeData,this);
        //listView = findViewById(R.id.gps_list_view);
        listView.setAdapter(myAdapter);

    }

    private void getItemsDataFooterPull() {
        Resources res =getResources();
        String[] modeData=res.getStringArray(R.array.modeData);
        Items item = findSelectItem();
        //List<GpsVo> deviceLis = sendService.getAll((currentPage * pageSize), pageSize,item.getId(),0);
        List<GpsVo> deviceLis = performJoinQuery(String.valueOf(item.getId()));
        if(deviceLis.size()>0){
            sendLisAll.addAll(deviceLis);
            //创建一个simpleAdapter
            myAdapter = new GpsAdapter(GpsListActivity.this, sendLisAll, R.layout.gps_list_item,modeData,this);
            currentPage ++;
            myAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 全选
     * @param
     */
    public void btnSelectAllList() {

        int count = listView.getCount();
        for (int i = 0; i < count; i++) {
            View lin = listView.getChildAt(i);
//
            checkBox = lin.findViewById(R.id.gps_list_items_checkbox);

            if(checkBox != null){
                checkBox.setChecked(true);
            }
            checkSta = true;
            did = lin.findViewById(R.id.did);
//            String id = (String) did.getText();
//            ids += id+",";

        }
    }

    /**
     * 全不选
     * @param
     */
    public void btnNoList() {

        int count = listView.getCount();
        for (int i = 0; i < count; i++) {
            View lin = listView.getChildAt(i);
//            lin.setFocusable(false);
//
//            checkBox = lin.findViewById(R.id.send_list_items_checkbox);
//            if(checkBox != null){
//                checkBox.setChecked(false);
//            }

            checkSta = false;
            did = lin.findViewById(R.id.did);
//            String id = (String) did.getText();
//            ids += id+",";
//            System.out.println("----ids----"+ids);
        }
        ids = "";
        updataData();
    }

    /**
     * 接口方法，响应ListView按钮点击事件
     */
    @Override
    public void clickListener(View v) {
        System.out.println("---------------------------v= "+v.getId());
        int id = v.getId();
        if(id>0){
            idlis.add(id);
        }else {
            String id1 = String.valueOf(id).substring(1);
            for (int i = 0; i < idlis.size(); i++) {
                if(idlis.get(i) == Integer.parseInt(id1)){
                    idlis.remove(i);
                }
            }

        }
        System.out.println("---------------------------idlis= "+idlis);
        ids = "";
        for (int i = 0; i < idlis.size(); i++) {
            ids += idlis.get(i)+",";
        }
    }

    @Override
    public boolean clickRemoveListener(int position) {
        removeItemsDataUpdata(position);
        updateItem(position);
        return true;
    }
    private void removeItemsDataUpdata(int position) {
        Resources res =getResources();
        String[] modeData=res.getStringArray(R.array.modeData);
        Items item = findSelectItem();
        List<GpsVo> deviceLis = performJoinQuery(String.valueOf(item.getId()));
        if(deviceLis.size()>0){
            sendLisAll.remove(position);
            sendLisAll.addAll(deviceLis);
            //创建一个simpleAdapter
            myAdapter = new GpsAdapter(GpsListActivity.this, sendLisAll, R.layout.gps_list_item,modeData,this);
            //myAdapter.notifyDataSetChanged();
        }
    }
    private void updateItem(int position) {
        /**第一个可见的位置**/
        int firstVisiblePosition = listView.getFirstVisiblePosition();
        /**最后一个可见的位置**/
        int lastVisiblePosition = listView.getLastVisiblePosition();

        /**在看见范围内才更新，不可见的滑动后自动会调用getView方法更新**/
        if (position >= firstVisiblePosition && position <= lastVisiblePosition) {
            /**获取指定位置view对象**/
            View view = listView.getChildAt(position - firstVisiblePosition);
            myAdapter.getView(position, view, listView);
        }

    }

}